package com.lianzhihui.romeex.ui.account;

import android.content.Intent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.lianzhihui.romeex.adapter.MnemonicsWordAdapter;
import com.lianzhihui.romeex.base.AppConfig;
import com.lianzhihui.romeex.bean.user.CountryCode;
import com.lianzhihui.romeex.bean.user.WalletInfo;
import com.lianzhihui.romeex.R;
import com.lianzhihui.romeex.inter.DialogListener;
import com.lianzhihui.romeex.ui.base.BaseActivity;
import com.lianzhihui.romeex.utils.JS2AndroidUtil;
import com.lianzhihui.romeex.utils.LogUtil;
import com.lianzhihui.romeex.utils.RecyclerItemDecoration;
import com.lianzhihui.romeex.mvp.view.LoginView;
import com.lianzhihui.romeex.widget.dialog.BatDialog;
import com.lianzhihui.romeex.widget.dialog.CustomConfirmDialog;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * ProjectName:    NBN
 * ClassName:      MnemonicWordActivity
 * Description:    助记词 界面
 * Author:         echo
 * CreateDate:     2019/10/24 13:45
 * UpdateUser:     更新者
 * UpdateDate:     2019/10/24 13:45
 * UpdateRemark:   更新说明
 * Version:        1.0
 */
public class MnemonicWordActivity extends BaseActivity implements LoginView {


    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.tv_private_key)
    TextView tv_private_key;
    @BindView(R.id.tv_copy)
    TextView tv_copy;
    @BindView(R.id.iv_qrcode)
    ImageView iv_qrcode;
    @BindView(R.id.mBridgeWebView)
    BridgeWebView mBridgeWebView;
    private WalletInfo walletInfo;
    private JS2AndroidUtil jS2AndroidUtil;
    private boolean finishLoad = false;
    private boolean isManage;
    private WalletInfo walletInfoCache;
    private MnemonicsWordAdapter mnemonicsWordAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_mnemonic_word;
    }

    @Override
    protected void initView() {
        setTitle(getResources().getString(R.string.toolbar_wallet_help_rember));
        isManage = getIntent().getBooleanExtra("isManage", false);
        walletInfoCache = (WalletInfo) getIntent().getSerializableExtra("walletInfo");
        jS2AndroidUtil = new JS2AndroidUtil(this, this);

        mBridgeWebView.addJavascriptInterface(jS2AndroidUtil, "Android");
        mBridgeWebView.setDefaultHandler(new DefaultHandler());
        mBridgeWebView.loadUrl("file:///android_asset/index.html");
        mBridgeWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    if (!finishLoad) {
                        createWallet();
                    }
                    finishLoad = true;
                }
            }
        });

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        RecyclerItemDecoration decoration = new RecyclerItemDecoration(10, 3);
        mRecyclerView.addItemDecoration(decoration);
        mRecyclerView.setLayoutManager(gridLayoutManager);
        mnemonicsWordAdapter = new MnemonicsWordAdapter(new ArrayList<>());
        mRecyclerView.setAdapter(mnemonicsWordAdapter);
        showLoading(getResources().getString(R.string.loading_create_wallet));
    }

    @Override
    protected void initData() {

    }

    public void createWallet() {
        jS2AndroidUtil.setWalletType(1);
        mBridgeWebView.evaluateJavascript("javascript:createWallet()", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String data) {

            }
        });
    }


    @Override
    public void setAccountData(WalletInfo data) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                walletInfo = data;

                walletInfo.setSaftyCode(walletInfoCache.getSaftyCode());
                walletInfo.setUserName(walletInfoCache.getUserName());
                //地址
                tv_address.setText(walletInfo.getAddress());
                //私钥
                tv_private_key.setText(walletInfo.getCompressedPrivkey());
                List<String> wordsList = Arrays.asList(data.getMnemonicWords().split(" "));
                mnemonicsWordAdapter.setNewData(wordsList);
//                showSafetyDialog();
                LogUtil.error("wallet", "1: " + walletInfo.toString());
                getKeyStore(data.getCompressedPrivkey(), data.getSaftyCode());

            }
        });
    }

    /**
     * 获取 ks
     *
     * @param data
     */
    @Override
    public void setWalletData(WalletInfo data) {
        walletInfo.setCiphertext(data.getCiphertext());
        LogUtil.error("wallet", "2: " + walletInfo.toString());
    }

    /**
     * 生成 ks
     *
     * @param pk
     * @param safetycode
     */
    public void getKeyStore(String pk, String safetycode) {

        jS2AndroidUtil.setWalletType(3);
        String jsFunction = "javascript:pk2Keystore('" + pk + "','" + safetycode + "')";
        mBridgeWebView.evaluateJavascript(jsFunction, new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String data) {
                dismissLoading();
            }
        });
    }

    /**
     * 安全弹窗，已弃用
     */
    private void showSafetyDialog() {
        CustomConfirmDialog customConfirmDialog = new CustomConfirmDialog(this);
        customConfirmDialog.setTitle(getString(R.string.nbn_safe_remind_string));
        customConfirmDialog.setDescribe(getString(R.string.nbn_safe_remind_info));
        customConfirmDialog.setButton(getString(R.string.nbn_i_know_string));
        customConfirmDialog.show();
    }

    @Override
    public void setImportData(WalletInfo data) {

    }

    @Override
    public void setSyncData(boolean success, int code) {

    }

    @Override
    public void setCountryCodeData(List<CountryCode> data) {

    }

    @Override
    public void setPhoneCodeData(String data) {

    }

    @Override
    public void setSyncPhoneCodeData(String data) {

    }

    @OnClick({R.id.bt_next_step, R.id.tv_address, R.id.tv_copy, R.id.iv_qrcode})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_next_step:

                //弹窗
                BatDialog batDialog = new BatDialog(this);
                batDialog.setListener(new DialogListener() {
                    @Override
                    public void onPassed() {
                        Intent intent = new Intent(mActivity, VerifyMnemonicWordActivity.class);
                        intent.putExtra("walletInfo", walletInfo);
                        intent.putExtra("isManage", isManage);
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    public void onFail() {

                    }
                });
            batDialog.show();
                break;
            case R.id.tv_address:
                copyString(tv_address.getText().toString().trim());
                break;
            case R.id.tv_copy:
                copyString(tv_private_key.getText().toString().trim());
                break;
            case R.id.iv_qrcode:
                Intent intent2 = new Intent(this, PKQRActivity.class);
                intent2.putExtra(AppConfig.PRIVATE_KEY, walletInfo.getCompressedPrivkey());
                startActivity(intent2);
                break;
            default:
                break;
        }
    }

    @Override
    public void setFailure() {
        dismissLoading();
    }
}
